package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TradeSourceOrderBean;
import com.atguigu.bean.TradeSourceOrderBean;
import com.atguigu.func.DimAsyncFunction;
import com.atguigu.func.WindowFuncUtil;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.KafkaUtil;
import com.atguigu.utils.MyClickHouseUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: DwsTradeSourceOrderWindow
 * Package: com.atguigu.app.dws
 * Description:
 *
 * @Author Lovxy
 * @Create 2023/5/17 20:02
 * @Version 1.0
 */
public class DwsTradeSourceOrderWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //TODO 2.读取kafka dwd_trade_order_detail主题数据
        DataStreamSource<String> kafkaSource = env.fromSource(KafkaUtil.getKafkaSource("dwd_trade_order_detail", "dws_source_order")
                , WatermarkStrategy.noWatermarks(), "kafka-source");
        //TODO 3.转化为javaBean对象
        SingleOutputStreamOperator<TradeSourceOrderBean> mapDs = kafkaSource.map(new MapFunction<String, TradeSourceOrderBean>() {
            @Override
            public TradeSourceOrderBean map(String value) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                String sourceName = jsonObject.getString("source_name");
                BigDecimal finalAmount = jsonObject.getBigDecimal("final_amount");
                String userId = jsonObject.getString("user_id");
                String orderId = jsonObject.getString("order_id");
                Long createTime = jsonObject.getLong("create_time");


                return TradeSourceOrderBean.builder()
                        .SourceName(sourceName)
                        .orderAmount(finalAmount)
                        .userId(userId)
                        .ts(createTime)
                        .orderId(orderId)
                        .build();
            }
        });
        //TODO 4.提取时间戳生成WaterMark
        SingleOutputStreamOperator<TradeSourceOrderBean> mapDsWithWm = mapDs.assignTimestampsAndWatermarks(WatermarkStrategy.<TradeSourceOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<TradeSourceOrderBean>() {
                    @Override
                    public long extractTimestamp(TradeSourceOrderBean element, long recordTimestamp) {
                        return element.getTs();
                    }
                }));

        //TODO 5.按照user_id分组去重 求下单人数
        SingleOutputStreamOperator<TradeSourceOrderBean> mapDsKeyByUid = mapDsWithWm.keyBy(TradeSourceOrderBean::getUserId)
                .map(new RichMapFunction<TradeSourceOrderBean, TradeSourceOrderBean>() {
                    private ValueState<String> valueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("last-state", String.class);
                        //设置TTL
                        StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build();
                        stateDescriptor.enableTimeToLive(ttlConfig);
                        valueState = getRuntimeContext().getState(stateDescriptor);
                    }

                    @Override
                    public TradeSourceOrderBean map(TradeSourceOrderBean value) throws Exception {
                        String lastDt = valueState.value();
                        String curDt = DateFormatUtil.toDate(value.getTs());
                        long uct = 0L;
                        if (lastDt == null || !lastDt.equals(curDt)) {
                            uct = 1L;
                            valueState.update(curDt);
                        }
                        value.setUserCount(uct);
                        return value;
                    }
                });

        //TODO 6.按照orderId分组去重 求下单次数
        SingleOutputStreamOperator<TradeSourceOrderBean> readyDs = mapDsKeyByUid.keyBy(TradeSourceOrderBean::getOrderId)
                .map(new RichMapFunction<TradeSourceOrderBean, TradeSourceOrderBean>() {
                    private ValueState<String> valueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("last-state", String.class);
                        //设置TTL
                        StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build();
                        stateDescriptor.enableTimeToLive(ttlConfig);
                        valueState = getRuntimeContext().getState(stateDescriptor);
                    }

                    @Override
                    public TradeSourceOrderBean map(TradeSourceOrderBean value) throws Exception {
                        String lastDt = valueState.value();
                        String curDt = DateFormatUtil.toDate(value.getTs());
                        long oct = 0L;
                        if (lastDt == null || !lastDt.equals(curDt)) {
                            oct = 1L;
                            valueState.update(curDt);
                        }
                        value.setOrderCount(oct);
                        return value;
                    }
                });
        //TODO 7.分组开窗聚合
        SingleOutputStreamOperator<TradeSourceOrderBean> resultDs = readyDs.keyBy(TradeSourceOrderBean::getSourceName)
                .window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<TradeSourceOrderBean>() {
                    @Override
                    public TradeSourceOrderBean reduce(TradeSourceOrderBean value1, TradeSourceOrderBean value2) throws Exception {
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        value1.setOrderCount(value1.getOrderCount()+value2.getOrderCount());
                        value1.setUserCount(value1.getUserCount()+value2.getUserCount());
                        return value1;
                    }
                }, new WindowFunction<TradeSourceOrderBean, TradeSourceOrderBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TradeSourceOrderBean> input, Collector<TradeSourceOrderBean> out) throws Exception {

                        WindowFuncUtil.setTes(window,input,out);
                    }
                });

        resultDs.print("resultDs>>>>");
        //TODO 9.写出到Clickhouse
        resultDs.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_trade_source_order_window values(?,?,?,?,?,?,?)"));

        env.execute();

    }
}
